package algorthm.systemTraning.mergeSort.countRange;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Random;

/**
 * @className: NumberComparator
 * @Description: 从一个数组 A 中找出，和在 [l , r] 内所有子集
 * @Author: wangyifei
 * @Date: 2022/9/26 14:03
 */
public class NumberComparator {
    private static Logger logger = LoggerFactory.getLogger(NumberComparator.class);
    public static int countRange(int[] array , int l , int r){
        if(array == null || array.length == 0){
            return -1 ;
        }
        int ans = 0 ;
        int[] preSum = new int[array.length];
        int sum = 0 ;
        // 计算前置和
        for(int i = 0 ; i < array.length ; i++){
            preSum[i] = sum + array[i];
            sum = preSum[i];
        }
        int rangeSum = 0 ;
        for(int i = 0 ; i < preSum.length ; i++){
            rangeSum = preSum[i];
            if(isInRange(rangeSum , l , r)){
                ans++;
            }
            for(int j = i + 1 ; j < preSum.length ; j++){
                rangeSum = preSum[j] - preSum[i];
                if(isInRange(rangeSum , l , r)){
                    ans++;
                }
            }
        }
        return ans ;
    }
    public static int[] rangeArray(int range , int size){
        Random r = new Random();
        int s = r.nextInt(size) + 1;
        int[] ans = new int[s] ;
        for(int i = 0 ; i < s ; i++){
           ans[i] = r.nextInt(range);
        }
        return ans ;
    }
    public static void compare(int range , int arraySize , int times){
        int[] array = null;
        int l = 0 ;
        int r = 0 ;
        int[] arrayBack = null ;
        Random ran = new Random();
        for(int i = 0 ; i < times ; i++){
            array = rangeArray(range , arraySize);
            arrayBack = Arrays.copyOf(array , array.length);
            l = ran.nextInt(range);
            while(r < l){
                r = ran.nextInt(range);
            }
            int ans1 = CountRange.countRange(array , l , r);
            int ans2 = countRange(array , l , r);
            if(ans1 != ans2){
                if(arrayBack.length < 15){
                    System.out.println("ans1:"+ans1+" , ans2:" + ans2 + " , l:" + l + " , r:" + r);
                    System.out.println("array:" + Arrays.toString(arrayBack));
                }
            }
        }
    }
    public static boolean isInRange(int sum , int l , int r){
        if(sum >= l && sum <= r){
           return true ;
        }
        return false ;
    }
    public static void main(String[] args){
//        int[] array = {12, 11 , -9 , 11 , 87};
//        int l = 2 ;
//        int r = 33;
//        System.out.println(countRange(array , l , r));
//        System.out.println(countRange(new int[]{32} , l , r));
//        System.out.println(countRange(null , l , r));
        compare(100 , 122 , 10000098);
    }
}
